import { Inject, Injectable } from '@nestjs/common';
import * as Minio from 'minio';
import { PrismaCommonService } from './middleware/prisma/prisma.service';
import { buildRegionTree } from './utils/buildRegionTree';
import { RabbitmqService } from '@app/rabbitmq';
import { GrpcService } from '@app/grpc';

@Injectable()
export class CommonService {
  @Inject('MINIO_CLIENT')
  private minioClient: Minio.Client;

  @Inject(PrismaCommonService)
  private prismaService: PrismaCommonService;

  @Inject(RabbitmqService)
  rabbitmqService: RabbitmqService;

  @Inject(GrpcService)
  grpcService: GrpcService;

  async upload(name: string) {
    return this.minioClient.presignedPutObject('dev', name, 3600);
  }

  async list() {
    const regions = await this.prismaService.region.findMany();
    const regionTree = buildRegionTree(regions);
    const result = { list: regionTree };
    return result;
  }

  async shortList() {
    return await this.prismaService.short.findMany();
  }

  /**
   * rabbitmq 异步通信
   * 客户端 发送
   */
  async getHello() {
    for (let i = 1; i <= 10; i++) {
      // 模拟发送1000条消息
      const user = { id: i, name: `User ${i}` }; // 模拟用户数据
      try {
        await this.rabbitmqService.send('user_retrieved', user);
        console.log(`消息 ${i} 已发送`);
      } catch (error) {
        console.log(`发送消息 ${i} 时出错`, error);
      }
    }

    return 'Hello World! news';
  }
  /**
   * gRPC 跨语言通信
   * 客户端 调用
   * @returns 调用gRPC传递数据
   */
  async getUser(id: number) {
    const user = await this.grpcService.getUser(id).toPromise();
    console.log('收到用户信息:', user);
    return user;
  }
}
